<template>
    <div class='search-container'>
        <navcon></navcon>
        <navsearch :searchVo="searchVo"></navsearch>

        <div class="main">

            <!-- 头部提示 -->
            <div class="head-tip">
                <ul>
                    <li class="all-categorys">
                        全部商品分类
                        <div class="all-category">
                            <ul class="all-list">
                                <!-- {{ treeList }} -->
                                <li v-for="value in treeList">
                                    <span class="category-one" @click="search(value.name)">{{ value.name }}</span>
                                    <div class="hide-banner">
                                        <div class="category-two-top">
                                            <div>
                                                <a href="" v-for="chValue1 in value.childrenCategory">
                                                    {{ chValue1['name'] }}
                                                </a>
                                            </div>
                                        </div>
                                        <div class="categoty-item">
                                            <div class="categoty-item" v-for="chValue in value.childrenCategory">
                                                <div class="category-two">
                                                    <!--保证当前节点不能为空 -->
                                                    <a v-if="chValue.childrenCategory != null" href=""
                                                        @click="search(chValue['name'])">
                                                        {{ chValue['name'] }}
                                                        <i class="el-icon-arrow-right"></i>
                                                    </a>
                                                </div>
                                                <div class="category-third">
                                                    <a href="" v-for="chChvalue in chValue.childrenCategory"
                                                        @click="search(chChvalue['name'])">
                                                        {{ chChvalue['name'] }}
                                                    </a>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </li>
                            </ul>
                        </div>
                    </li>
                    <li @click="search('华为')">华为</li>
                    <li @click="search('小米')">小米</li>
                    <li @click="search('苹果')">苹果</li>
                    <li @click="search('微软')">微软</li>
                    <li @click="search('平板电脑')">平板电脑</li>
                    <li @click="search('蓝牙耳机')">蓝牙耳机</li>
                </ul>
            </div>
            <div class="now-position">
                全部商品 > {{ searchVo.keyword }}
            </div>
            <!-- 搜索提示 -->
            <div class="search-tip">
                <!-- 品牌 -->
                <div class="brand" v-if="brandList.length > 0">
                    <div class="brand-head">
                        <span>品牌：</span>
                    </div>
                    <div class="brand-info">
                        <ul>
                            <li class="brand-item" v-for="brand, index in brandList" v-if="index < 20"
                                :key="JSON.parse(brand).in">

                                <img :src="JSON.parse(brand).brandLog" alt="" class="brand-img">
                                <div class="brand-name" @click="changeBrand(JSON.parse(brand).name, JSON.parse(brand).id)">
                                    {{ JSON.parse(brand).name }}</div>
                            </li>
                        </ul>
                    </div>
                </div>
                <!-- 分类 -->
                <div class="category" v-if="categoryList.length > 0">
                    <div class="category-head head">
                        <span>分类：</span>
                    </div>
                    <div class="category-info">
                        <ul>
                            <li @click="changeCategory(JSON.parse(category).name, JSON.parse(category).id)"
                                class="category-item" v-for="category in categoryList" :key="JSON.parse(category).id">
                                <span class="category-name">{{ JSON.parse(category).name }}</span>
                            </li>
                        </ul>
                    </div>
                </div>
                <!-- 属性 -->
                <div class="attrs" v-if="attrList.length > 0">
                    <div class="attrs-item" v-for="attr in attrList">
                        <div class="attr-head head">
                            <span>{{ attr.attrName }}</span>
                        </div>
                        <div class="attr-info info">
                            <ul>
                                <li @click="changeAttrs(attr.attrName, value, attr.attrId)" class="attr-item"
                                    v-for="value in attr.value">
                                    <span class="attr-name">{{ value }}</span>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
            <!-- 详细搜索挑选 -->
            <div class="search-help">
                <div class="help">
                    <ul>
                        <li>
                            <span @click="sorted()" class="all-round">综合<i class="el-icon-caret-bottom"></i></span>
                        </li>
                        <li>
                            <div class="new-goods all-round">
                                新品<i class="el-icon-caret-bottom"></i>
                            </div>
                        </li>
                        <li>
                            <div class="all-round change-price" @click="sorted()">
                                价格
                                <div>
                                    <i :class="sorte == 'asc' ? 'el-icon-caret-top top blue' : 'el-icon-caret-top top'"></i>
                                    <i :class="sorte == 'desc' ? 'el-icon-caret-bottom bottom blue'
                                        : 'el-icon-caret-bottom bottom'"></i>
                                </div>
                            </div>
                        </li>
                        <li>
                            <ul class="bar-chart">
                                <!-- 点击事件时，添加类 change-color -->
                                <li @click="changePrice" @mouseenter="mouseenter(1, 349)" @mouseleave="mouseleave()">
                                    <span class="first-tip">8%的用户喜欢的价位</span>
                                    <span class="color first"></span>
                                </li>
                                <li @click="changePrice" @mouseenter="mouseenter(350, 1367)" @mouseleave="mouseleave()">
                                    <span class="second-tip">29%的用户喜欢的价位</span>
                                    <span class="color second"></span>
                                </li>
                                <li @click="changePrice" @mouseenter="mouseenter(1368, 3579)" @mouseleave="mouseleave()">
                                    <span class="third-tip">43%的用户喜欢的价位</span>
                                    <span class="color third"></span>
                                </li>
                                <li @click="changePrice" @mouseenter="mouseenter(3580, 8096)" @mouseleave="mouseleave()">
                                    <span class="fourth-tip">15%的用户喜欢的价位</span>
                                    <span class="color fourth"></span>
                                </li>
                                <li @click="changePrice" @mouseenter="mouseenter(8097, 39899)" @mouseleave="mouseleave()">
                                    <span class="five-tip">5%的用户喜欢的价位</span>
                                    <span class="color five"></span>
                                </li>
                            </ul>
                        </li>
                        <li>
                            <div class="all-round scope-price">
                                <input type="number" oninput="value=value.replace(/^[0]+[1-9]*/g,'')"
                                    v-model="searchVo.priceFrom">-
                                -<input type="number" oninput="value=value.replace(/^[0]+[1-9]*/g,'')"
                                    v-model="searchVo.priceTo">
                                <div class="border">
                                    <input type="number" oninput="value=value.replace(/^[0]+[1-9]*/g,'')"
                                        v-model="searchVo.priceFrom">-
                                    -<input type="number" oninput="value=value.replace(/^[0]+[1-9]*/g,'')"
                                        v-model="searchVo.priceTo">
                                    <div class="clear" @click="clearPrice()">清空</div>
                                    <div class="enter-price" @click="enterPrice()">确认</div>
                                </div>
                            </div>
                        </li>
                        <li>
                            <div class="all-round all-product-count">
                                <span class="total-count">
                                    共
                                    <span>{{ productLen }}+</span>
                                    件商品
                                    <span>{{ searchVo.pageNum }}</span>
                                    /{{ getPage(Math.ceil(productLen / searchVo.pageSize)) }}
                                </span>
                                <span :class="searchVo.pageNum == 1 ? 'public-page' : 'pre-page'" @click="prePage()">
                                    <i class="el-icon-arrow-left"></i>
                                </span>
                                <span
                                    :class="searchVo.pageNum >= productLen / searchVo.pageSize ? 'public-page' : 'next-page'"
                                    @click="nextPage()">
                                    <i class="el-icon-arrow-right"></i>
                                </span>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
            <!-- 搜索出来的商品展示 -->
            <div class="main-container" v-if="productList.length > 0">
                <div class="search-body">
                    <div class="search-item" v-for="product in productList">
                        <div class="head-img">
                            <img @click="goDeatil(product.spuId)" :src="product.spuImage" alt="">
                        </div>
                        <div class="product-price">
                            ￥{{ product.spuPrice }}
                        </div>
                        <div @click="goDeatil(product.spuId)" class="product-title" v-html="product.spuTitle">
                        </div>
                        <div class="author" v-html="'发布者: ' + product.nickname" @click="">
                        </div>
                        <div class="option">
                            <div class="add-cart" @click="goDeatil(product.spuId)">查看商品详情</div>
                            <div class="add-collect" @click="collect(product)">收藏</div>
                        </div>
                    </div>
                    <!-- 切换页 -->
                    <div style="position: absolute; right: 0px">
                        <el-pagination @prev-click="prePage" @next-click="nextPage" @current-change="currentChage"
                            :current-page="searchVo.pageNum" :page-size="searchVo.pageSize"
                            layout="prev, pager, next, jumper" :total="productLen">
                        </el-pagination>

                    </div>
                </div>
            </div>
            <div v-if="productList.length == 0">
                <el-empty :image-size="400"></el-empty>
            </div>

        </div>
        <bottom></bottom>
    </div>
</template>

<script>

import navcon from '../components/navcon.vue';
import navsearch from '../components/navsearch.vue';
import bottom from "../components/navbottom.vue"
import getUUID from '../utils/uuid';

export default {
    name: 'search',
    data() {
        return {
            categoryList: [],    // 分类信息
            brandList: [],      // 品牌信息
            attrList: [],   // 属性列表
            productList: [],    // 商品列表

            productLen: 99,   // 商品数量 
            searchList: [],   // 搜索的返回结果
            querySubmit: null,  // 子组件搜索按钮,控制搜索s
            collectVo: [],

            searchVo: {
                keyword: null,
                categoryId: null,
                category: null,
                brandId: null,
                brand: null,
                attrs: [],
                order: null,
                pageNum: 1,  // 当前在哪一页
                pageSize: 20,  // 一页的数据
                priceFrom: null,   // 低价位
                priceTo: null,    // 高价位
            },
            memberVo: [],
            sorte: "asc",    // 升序排序
            beforeForm: '',  // 鼠标移动进入前的价格
            beforeTo: '',    // 鼠标移动进入前的价格


            treeList: [],
        };
    },
    components: {
        navcon,
        navsearch,
        bottom
    },
    methods: {

        // 新品
        newProduct(){
            // 关键字为null，查询全部商品，进行时间排序，时间从大到小
            
        },


        // 切换页面时调用
        async currentChage(val) {
            this.searchVo.pageNum = val
            await this.getSearchInfo()
        },

        // 上一页
        async prePage() {
            if (this.searchVo.pageNum >= 2) {
                this.searchVo.pageNum--;
                await this.getSearchInfo()
            }
        },

        // 下一页
        async nextPage() {
            if (this.searchVo.pageNum < this.productLen / this.searchVo.pageSize) {
                let temp = this.searchVo.pageNum
                this.searchVo.pageNum++;
                await this.getSearchInfo()
                this.searchVo.pageNum = temp + 1
            }
        },

        /**
         * 柱形价格显示的点击事件
         */
        async changePrice() {
            this.beforeForm = this.searchVo.priceFrom
            this.beforeTo = this.searchVo.priceTo
            this.searchVo.priceFrom = this.beforeForm
            this.searchVo.priceTo = this.beforeTo
            await this.getSearchInfo()
        },

        /**
         * 鼠标键入时，价格输入显示
         * @param {*} form 
         * @param {*} to 
         */
        mouseenter(form, to) {
            this.beforeForm = this.searchVo.priceFrom
            this.beforeTo = this.searchVo.priceTo
            this.searchVo.priceFrom = form
            this.searchVo.priceTo = to
        },

        /**
         * 鼠标离开时，输入价格恢复默认
         */
        mouseleave() {
            this.searchVo.priceFrom = this.beforeForm
            this.searchVo.priceTo = this.beforeTo
        },

        /**
         * 排序搜索
         */
        async sorted(allRound) {
            if (allRound) {
                this.searchVo.order = ''
            } else {
                if (this.sorte == "asc") {
                    this.sorte = "desc"
                    this.searchVo.order = "1:" + this.sorte
                } else if (this.sorte == "desc") {
                    this.sorte = "asc"
                    this.searchVo.order = "1:" + this.sorte
                }
            }
            await this.getSearchInfo()
        },


        /**
         * 计算当前页
         * @param {*} page 
         */
        getPage(page) {
            if (page == 0) {
                return 1;
            } else {
                return page;
            }
        },

        // 前往商品详情页
        goDeatil(spuId) {
            this.$router.push({
                path: '/product/productdetail',
                query: {
                    spuId: spuId,
                    params: getUUID()
                }
            })
        },


        /**
         * 收藏商品
         */
        async collect(product) {
            this.collectVo.memberId = this.memberVo.id
            this.collectVo.spuId = product.spuId
            this.collectVo.spuImg = product.spuImage
            this.collectVo.spuName = product.spuTitle
            this.collectVo.price = product.spuPrice
            await this.$http({
                url: this.$http.adornUrl("/shitou-member/shitoumember/membercollectspu/createCollect"),
                method: 'post',
                data: this.$http.adornData(this.collectVo)
            }).then(({ data }) => {
                if (data.code == 200) {
                    this.$message({
                        type: 'success',
                        message: '收藏商品成功'
                    })
                } else if (data.code == 402) {
                    this.$router.push({ path: '/member/login' })
                } else {
                    this.$message({
                        type: 'warning',
                        message: data.message
                    })
                }

            })
        },


        /**
         * 清除价格区间
         */
        async clearPrice() {
            this.searchVo.priceFrom = ''
            this.searchVo.priceTo = ''
            await this.getSearchInfo()
        },


        /**
         * 通过价格区间进行搜索
         */
        async enterPrice() {
            let form = this.searchVo.priceFrom
            let to = this.searchVo.priceTo
            if (form < 0 || form > to) {
                await this.clearPrice()
            } else {
                await this.getSearchInfo()
            }
        },


        /**
         * 获取搜索属性
         */
        async changeAttrs(name, value, id) {
            let len = this.searchVo.attrs.length
            let tag = true;
            for (let i = 0; i < len; i++) {
                // 两者名称相等，说明之前已经选中过了，现在重新赋值
                if (this.searchVo.attrs[i].attrName == name) {
                    this.searchVo.attrs[i].attrValue = value
                    this.searchVo.attrs[i].arrtId = id
                    tag = false;
                    break;
                }
            }
            // 判断是否将这个属性加入到搜书数据中
            if (tag) {
                this.searchVo.attrs.push({
                    attrId: id,
                    attrName: name,
                    attrValue: value
                })
            }
            await this.getSearchInfo()
        },


        /**
         * 获取品牌
         */
        async changeBrand(name, id) {
            this.searchVo.brand = name;
            this.searchVo.brandId = id;
            await this.getSearchInfo() // 品牌只有一行，搜索一次,进行初始化
            this.init()
        },


        /**
         * 获取分类
         */
        async changeCategory(name, id) {
            this.searchVo.category = name;
            this.searchVo.categoryId = id;
            await this.getSearchInfo() // 分类只有一行，搜索一次,进行初始化
            this.init()
        },


        /**
         * 搜索数据,分页搜索
         */
        async getSearchInfo() {
            await this.$http({
                url: this.$http.adornUrl("/shitou-search/shitousearch/search/search"),
                method: 'post',
                data: this.$http.adornData(this.searchVo)
            }).then(({ data }) => {
                if (data.code == 200) {
                    this.searchList = data.data == null ? [] : data.data
                    this.categoryList = data.data.category == null ? [] : data.data.category.value
                    this.brandList = data.data.brand == null ? [] : data.data.brand.value
                    this.attrList = data.data.attrs == null ? [] : data.data.attrs
                    this.productList = data.data.products == null ? [] : data.data.products
                    this.getProduct()
                } else {
                    // 没有获得数据
                    this.initShow()
                    this.$message({
                        type: 'warning',
                        message: data.message
                    })
                }
            })
        },


        // 搜索数据, 不分页，查询全部,根据条件,,,,,,主要用于获取所有数据的条数
        /// 不太好使，待修改
        async getProduct() {
            const _ = require('lodash');
            let temp = _.cloneDeep(this.searchVo);
            temp.pageNum = 1
            temp.pageSize = 10000
            await this.$http({
                url: this.$http.adornUrl("/shitou-search/shitousearch/search/search"),
                method: 'post',
                data: this.$http.adornData(temp)
            }).then(({ data }) => {
                if (data.code == 200) {
                    this.productLen = data.data.total
                } else {
                    this.$message({
                        type: 'warning',
                        message: data.message
                    })
                }

            })
        },


        /**
         * 展示数据初始化
         */
        initShow() {
            this.searchList = []
            this.categoryList = []
            this.brandList = []
            this.attrList = []
            this.productList = []
            this.productLen = 0
        },


        /**
         * 搜索数据初始化
         */
        init() {

            let initData = {
                keyword: this.searchVo.keyword,
                categoryId: null,
                category: null,
                brandId: null,
                brand: null,
                attrs: [],
                order: null,
                pageNum: 1,  // 当前在哪一页
                pageSize: 20,  // 一页的数据
                priceFrom: null,   // 低价位
                priceTo: null,    // 高价位
            }
            this.searchVo = initData;
        },


        // 获得商品分类的树形数据
        getTreeList() {
            this.$http({
                url: this.$http.adornUrl("/shitou-product/shitouproduct/category/treeList"),
                method: 'get'
            }).then(({ data }) => {
                let len = data.data.length;
                if (len > 20)
                    this.treeList = data.data.slice(0, 20)
                else this.treeList = data.data
            })
        },


        // 搜索数据
        async search(keyword) {
            this.searchVo.keyword = keyword;
            this.init()

            await this.getSearchInfo();
        },

    },
    async created() {
        this.getTreeList()
        let member = await this.$memberInfo()
        if (member != null) {
            this.memberVo = member
        }
        this.searchVo.keyword = this.$route.query.search

        if (this.searchVo.keyword != "") {
            await this.getSearchInfo()
        }
    }
}
</script>

<style scoped>
@import url("../utils/css/search.css");
</style>